window.onload = function () {
    fullTable(books)
}

function fullTable(array) {
    let str = "";
    array.forEach(n => {
        str += `<tr><td><img src=${n.src} width="30" height="40"></td><td>${n.bookName}</td><td>${n.author}</td><td>${n.price}</td>
     <td><input type="button" value="查看" onclick="showBook(${n.code})"><input type="button" value="添加到购物车" onclick="add(${n.code})"></td>  
     </tr>`
    });
    $("data").innerHTML = str;
}

/**
 * 通过id获取元素事件
 * @param id
 * @returns {HTMLElement}
 */
function $(id) {
    return document.getElementById(id);
}

/**
 * 查找图书
 */
function showBooks() {
    var nameStr = $("bookName").value;
    var array = books.filter(n => n.bookName.startsWith(nameStr));
    fullTable(array)
}

/**
 * 查看图书
 */
function showBook(code) {
    $("showDiv").style.visibility = "visible";
    var obj = books.find(n => n.code == code);
    $("bookSpan").innerHTML = obj.bookName
    $("authorSpan").innerHTML = obj.author
    $("dateSpan").innerHTML = obj.date
    $("priceSpan").innerHTML = obj.price
    $("imgSrc").src = obj.src

}

// 创建一个新数组
var shopping = []

/**
 * 购物车表格
 */
function shTable() {
    let str = "";
    let nums;
    var numss = []
    shopping.forEach(n => {
        nums = n.num * (n.book.price);
        numss.push(nums)
        str += `<tr><td>${n.book.bookName}</td><td>${n.book.price}</td><td><input type="text" value="${n.num}" onblur="update(${n.book.code})" id="${n.book.code}"></td><td><span>${nums}</span></td><td><input type="button" value="移除商品" onclick="remove(${n.book.code})"></td></tr>`
    })
    console.log(numss)
    $("data1").innerHTML = str;
    nums=0;
    for (let i = 0; i < numss.length; i++) {
        nums+=numss[i]
    }
    $("data2").innerHTML = nums;
}

/**
 * 添加到购物车
 * @param code
 */
function add(code) {
    $("showBuy").style.visibility = "visible";
    var obj = shopping.find(n => n.book.code === code)
    if (obj != null) {
        obj.num++;
    } else {

        var book = books.find(n => n.code == code);
        var shop = {book, num: 1};
        shopping.push(shop);
        console.log(shopping)
    }
    shTable()
}

/**
 * 退出
 */
function quit() {
    $("showBuy").style.visibility = "hidden";
}

/**
 * 移除商品
 */
function remove(code) {
    console.log(code)
    for (var i = 0, vlen = shopping.length; i < vlen; i++) {
        if (shopping[i].book.code == code) {
            shopping.splice(i, 1)
            shTable()
        }
    }
}

/**
 * 更新商品数量
 * @param code
 */
function update(code) {
    console.log(code)
    var obj = shopping.find(n => n.book.code == code)
    prices = $("" + code).value
    obj.num = prices;
    shTable()
}